/**
 * Copyright (C), 2020-2020, 软件公司
 * FileName: TxSendException
 * Author:   cakin
 * Date:     2020/4/25
 * Description: 事务生产者发送消息后异常
 */
package com.rabbitmq.tx;

/**
 * @ClassName: TxSendException
 * @Description: 事务生产者发送消息后异常
 * @Date: 2020/4/25
 * @Author: cakin
 */

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.util.ConnectionUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.concurrent.TimeoutException;


/**
 * 生产者
 */
@Slf4j
public class TxSendException {

    /**
     * 队列名
     */
    private static final String QUEUE_NAME = "test_queue_tx";

    public static void main( String[] args ) throws IOException, TimeoutException {
        // 获取连接
        Connection connection = ConnectionUtils.getConnection();
        // 从连接开一个通道
        Channel channel = connection.createChannel();
        // 从通道声明一个队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        try {
            channel.txSelect(); // 开启事务

            // 发送消息
            String message = "hello, tx message exception";
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            log.info(" [x] Sent message : '" + message + "'");
            // 构造异常
            int i = 1 / 0;

            channel.txCommit(); // 提交事务
        } catch (ArithmeticException e) {
            channel.txRollback(); // 回滚事务
            log.info("send message exception txRollback");
        }

        channel.close();
        connection.close();
    }
}

